package com.common.shiro;

import com.common.util.MessageUtils;
import com.common.util.manager.AsyncManager;
import com.common.util.manager.factory.AsyncFactory;
import com.system.constant.CommonConstant;
import com.common.token.JwtToken;
import com.system.constant.Constants;
import com.system.util.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.stereotype.Component;

/**
 * @author zfc
 * @date 2023-04-20 16:16:48
 */
@Component
public class MyCredentialsMatcher  extends SimpleCredentialsMatcher {


    //使用自定义token
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        JwtToken jwtToken=(JwtToken) token;
        if (jwtToken.getPassword() == null){
            return true;
        }

        //获得用户输入的密码:(采用加盐(salt)的方式去检验)
        String inPassword = new String(jwtToken.getPassword());
        //获得数据库中的密码
        String username = String.valueOf(info.getPrincipals());
        //加上盐slat
        String dbPassword=(String) info.getCredentials();
        //进行密码的比对
        boolean equals = this.equals(StringUtils.md5(inPassword + CommonConstant.SLAT), dbPassword);
        if(!equals){
            //密码不匹配
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            return equals;
        }
        return equals;
    }


    /*@Autowired
    private UserMapper userService;

    //使用自定义token
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        JwtToken jwtToken=(JwtToken) token;
        if (jwtToken.getPassword() == null){
            return true;
        }
        //获得用户输入的密码:(可以采用加盐(salt)的方式去检验)
        String inPassword = new String(jwtToken.getPassword());
        //获得数据库中的密码
        String username = String.valueOf(info.getPrincipals());
        //获取盐
        String slat = userService.getUserByUsername(username).getSalt();
//        System.out.println(StringUtil.md5(inPassword + slat));
        String dbPassword=(String) info.getCredentials();
        //进行密码的比对
        return this.equals(StringUtil.md5(inPassword + slat), dbPassword);
    }*/
}
